package com.hmdp.utils;

import cn.hutool.Hutool;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @program: hm-dianping
 * @description:
 * @author: Feng
 * @create: 2023-03-09 14:52
 **/
//建造锁类
public class RedisSimpleLock implements ILock {
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
//    生成uuid,用来判断锁的归属
    private static final String ID_PREFIX = UUID.randomUUID().toString(true);


    public RedisSimpleLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(String key, Long ttl) {
//        注意拆箱
//        是给value加上变化
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name+key, ID_PREFIX+Thread.currentThread().getId(),ttl, TimeUnit.SECONDS));

    }



    @Override
    public void releaseLock(String key) {
        releaseLockWithLua(key);
    }
//    在启动的时候就进行加载
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public void releaseLockWithLua(String key) {
        key = KEY_PREFIX+name+key;
        String threadValue = ID_PREFIX + Thread.currentThread().getId();
//        调用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key),threadValue);
    }


    public void releaseLockWithJava(String key) {
        key = KEY_PREFIX+name+key;
        String value = stringRedisTemplate.opsForValue().get(key);
        String threadValue = ID_PREFIX + Thread.currentThread().getId();
        if(value.equals(threadValue))
            stringRedisTemplate.delete(key);
    }

}
